<?php
/**
 * Created by PhpStorm.
 * User: shaowei
 * Date: 2019/4/22
 * Time: 下午8:21
 */

namespace App\Http\Services;


use App\Http\Model\FinanceRoomWealth;
use App\Http\Model\FinanceUserWallet;
use App\Http\Model\FinanceWealth;
use App\Http\Model\Friends;
use App\Http\Model\Hint;
use App\Http\Model\Room;
use App\Http\Model\RoomHostMicro;
use App\Http\Model\RoomHot;
use App\Http\Model\RoomMicro;
use App\Http\Model\RoomUser;
use App\Http\Model\System;
use App\Http\Model\SystemConfig;
use App\Http\Model\User;
use App\Http\Model\Mall;
use Illuminate\Support\Facades\Redis;
use App\Http\Model\RoomFrame;

class RoomHotServices extends CommonServices
{
    private $model_room_hot;
    private $model_room_user;
    private $model_finance_room_wealth;
    private $model_room;
    private $modelFinanceWealth;
    private $modelFinanceUserWallet;
    private $modelUser;
    private $modelRoomMicro;
    private $model_friend;
    private $model_room_host_micro;
    protected $mallGoods;
    protected $model_room_micro;
    protected $roomFrameModel;
    protected $model_system;

    protected $redis_room_cover_special = 'ROOM:COVER:SPECIAL';//房间活动特殊封面

    public function __construct()
    {
        $this->model_room_hot = new RoomHot();
        $this->model_room_user = new RoomUser();
        $this->model_finance_room_wealth = new FinanceRoomWealth();
        $this->model_room = new Room();
        $this->modelFinanceWealth = new FinanceWealth();
        $this->modelFinanceUserWallet = new FinanceUserWallet();
        $this->modelUser = new User();
        $this->modelRoomMicro = new RoomMicro();
        $this->model_friend = new Friends();
        $this->model_room_host_micro = new RoomHostMicro();
        $this->mallGoods = new Mall;
        $this->model_room_micro = new RoomMicro();
        $this->roomFrameModel = new RoomFrame();
        $this->model_system = new System();
    }

    public function none_top($num){
        $result = [];
        //所有房间信息
        $list = $this->model_room_hot->getAllRoomHotIdData();
        $list = empty($list) ? [] : json_decode($list, true);

        $listEx = [];
        foreach($list as $val) {
            if(isset($val['b']) && $val['b']==0) {
                //获取人数
                $userNum = $this->model_room_user->get_users_count($val['r']);
                if(empty($userNum)) {
                    continue;
                }
                //获取热度
                $hotNum = $this->model_room_hot->get($val['r']);
                $listEx[] = [
                    'roomId' => $val['r'],
                    'hotNum' => $hotNum
                ];
            }
        }

        //排序截取
        if(!empty($listEx)) {
            array_multisort(array_column($listEx, 'hotNum'), SORT_DESC, $listEx);
            $listEx = array_slice($listEx, 0, $num);
            $result = array_column($listEx, 'roomId');
        }

        return $result;
    }

    /**
     * 设置密码
     * @param $roomId
     */
    public function setPassword($roomId){
        $this->model_room_hot->del($roomId);
    }

    /**
     * 关闭房间
     * @param $roomId
     */
    public function closeRoom($roomId){
        $this->model_room_hot->del($roomId);
    }

    public function get_user_is_remain_room($user_id ,$room_id){
        return $this->modelUser->get_user_is_remain_room($user_id,$room_id);
    }

    public function set_user_remain_room($user_id ,$room_id){
        return $this->modelUser->set_user_remain_room($user_id ,$room_id);
    }

    public function reorderRoomId($data){
        $res = $this->model_room->get_rooms_by_ids($data);
        foreach ($res as $k=>&$r) {
            if($this->model_room->getIsGameRoom($r['room_type']['id'])){
                $r['filter_one'] = 1;
            }else{
                $r['filter_one'] = 0;
            }
            $r['filter_two'] = 0;
            $r['filter_three'] = count($res) - $k;
        }
        $orderByList = array_column($res, 'filter_one');
        $orderByList2 = array_column($res, 'filter_two');
        $orderByList3 = array_column($res ,'filter_three');
        array_multisort($orderByList, SORT_DESC,$orderByList2, SORT_DESC,$orderByList3, SORT_DESC, $res);
        return array_column($res ,'room_id');
    }

    /**
     * 获取已开启CBD房间列表
     * 第一页 page=0 包含置顶列表
     */
    public function hot_v3($userId, int $page, int $type) {
        $now = time();

        if($type < -2 || $page < 0){
            return [];
        }
        $limit = 20;
        
        //新版首页需求type=-2 固定热度从高到低排序10条(默认可更改)
        if($type == -2){
            $sysConfig = $this->model_system->get_config();
            $configShow = isset($sysConfig['show_index_hot_limit']) ? $sysConfig['show_index_hot_limit']['value'] : 10;
            $limit = $configShow;
        }

        //获取置顶
        $dataTop = [];
        $topRoomIds = [];
        if ($type=='-1'){
            $dataTop = $this->special_channel_recommended_room($page);
            if(!empty($dataTop)) {
                $topRoomIds = array_column($dataTop, 'room_id');
            }
        }

        $ret_hot_rooms_id = [];
        $ret_hot_rooms_data = [];
        $hasRoomIds = [];//已返回房间ID
        do{
            //已经返回过的不应再次返回 查询已经给用户返回过的roomId 不是第一页才查询
            if($page > 0) {
                $hasRoomIds = $this->model_room_hot->getHasRetHotIdsToUser($userId, $type);
                $hasRoomIds = json_decode($hasRoomIds, true);
            }

            //所有CBD房间
            $allRoomHotIdList = [];
            $list = $this->model_room_hot->getAllRoomHotIdData();
            $list = json_decode($list, true);
            foreach($list as $val) {
                //未被返回的
                if(!empty($hasRoomIds) && in_array($val['r'], $hasRoomIds)) {
                    continue;
                }
                //不再置顶中的 只在第一页限制 之后的根据已返回记录控制
                if($page==0 && !empty($topRoomIds) && in_array($val['r'], $topRoomIds)) {
                    continue;
                }
                //如果选择了类型
                if($type>0 && $val['t']!=$type) {
                    continue;
                }
                //若type=-1则去除娱乐房间数据
                $roomInfo = $this->model_room->get_room($val['r']);
                if($type == -1 && ($roomInfo['room_type']['type_name'] == '娱乐' || $roomInfo['room_type']['type_name'] == '交友')){
                    continue;
                }
                
                //房间特殊隐藏
                if(isset($roomInfo['is_hide']) && $roomInfo['is_hide'] == 1){
                    continue;
                }

                //获取人数
                $userNum = $this->model_room_user->get_users_count($val['r']);
                // if(empty($userNum)) {
                //     continue;
                // }
                //CBD房间
                if(isset($val['b']) && $val['b']==1) {
                    $allRoomHotIdList[] = $val;
                }

                
            }

            //没有数据直接返回
            if(empty($allRoomHotIdList)) {
                break;
            }
            //根据热度排序
            array_multisort(array_column($allRoomHotIdList, 'h'), SORT_DESC, $allRoomHotIdList);

            //数组截取
            $allRoomHotIdList = array_slice($allRoomHotIdList, 0, $limit);
            $ret_hot_rooms_id = array_column($allRoomHotIdList, 'r');

        } while(false);

        //从es获取数据
        // $ret_hot_rooms_data = $this->_getRoomsByIdsFromEs($ret_hot_rooms_id, $page, $limit);
        $ret_hot_rooms_data = $this->_getRoomsByIdsFromEs($ret_hot_rooms_id, $page, 10000);
        // write_log('ret_hot_rooms_data', var_export($ret_hot_rooms_data, true),true);
        //排序
        array_multisort(array_column($ret_hot_rooms_data, 'micro_user_count'), SORT_DESC, array_column($ret_hot_rooms_data, 'hot_sort'), SORT_DESC, $ret_hot_rooms_data);
        //整理返回值
        $result = [];
        foreach($dataTop as $val) {
            if($page == 0) {
                $specialImg = Redis::get($this->redis_room_cover_special.$val['room_id']);
                $val['activity_special_img'] = empty($specialImg) ? '' : build_image('/'.$specialImg);    
                $result[] = $val;
                $hasRoomIds[] = $val['room_id'];
            }
        }
        foreach($ret_hot_rooms_data as $val) {
            $specialImg = Redis::get($this->redis_room_cover_special.$val['room_id']);
            $val['activity_special_img'] = empty($specialImg) ? '' : build_image('/'.$specialImg);

            //房间边框
            $val['room_frame'] = $this->roomFrameModel->getRoomFrameByRoomIdTime($val['room_id'], $now);

            $result[] = $val;
            $hasRoomIds[] = $val['room_id'];
        }
        //设置已返回房间ID
        $this->model_room_hot->setHasRetHotIdsToUser($userId, $type, json_encode($hasRoomIds));

        return $result;
    }

    /**
     * 获取置顶渠道 置顶的推荐房间
     * type 0=获取数据 1=不获取数据
     */
    public function special_channel_recommended_room($type=0) {
        $now = time();
        $top_rooms_data = [];
        $roomTopList = $this->model_room->getRoomTopAll($now);
        if(empty($type)) {
            $roomIds = array_column($roomTopList, 'room_id');
            $roomTopList = array_column($roomTopList, 'sort_num', 'room_id');
            if(!empty($roomIds)) {
                $top_rooms_data = $this->_getRoomsByIdsFromEs($roomIds, 0, count($roomIds));
                if(!empty($top_rooms_data)) {
                    foreach($top_rooms_data as $key=>$val) {
                        $top_rooms_data[$key]['sort_num'] = empty($roomTopList[$val['room_id']]) ? 9999999 : $roomTopList[$val['room_id']]; 
                    }
                    array_multisort(array_column($top_rooms_data, 'sort_num'), SORT_ASC, $top_rooms_data);
                }
            }
        }else{
            $top_rooms_data = $roomTopList;   
        }
        
        //置顶逻辑房间获取房间封面
        if(!empty($top_rooms_data))
        {
            foreach($top_rooms_data as $k=>$v){
                $specialImg = Redis::get($this->redis_room_cover_special.$v['room_id']);
                if (!empty($specialImg))
                {
                    $top_rooms_data[$k]['activity_special_img'] = build_image($specialImg); //特殊房间活动icon
                }else{
                    $top_rooms_data[$k]['activity_special_img'] = ''; //默认为空
                }
            }
        }
        
        return $top_rooms_data;
    }


    public function _getRoomsByIdsFromEs($roomIds,$page, $pageSize){
        if(empty($roomIds)){
            return [];
        }
        $query = [
            "bool" => [
                'must' => [
                    "terms" => ['_id' => $roomIds,],
                ],
            ],
        ];
        $rdata = $this->model_room_hot->queryRoomHotFromEs($query, $page, $pageSize);
        return $rdata;
    }

    /**@params null
     * @return bool true成功，false失败
     * @desc 定时任务，每n秒刷新一次es room数据
     * @author zxiaofee
     * @date 2021.12.28
     */
    public function update_es_room_data() {
        //所有已开启的房间
        $list = $this->model_room->getAllRoomOpenList();
        $roomIds = [];
        foreach($list as $key=>$val) {
            [$roomId, $type] = explode(':', $key);
            $roomIds[] = $roomId;
        }
        $hot_room_ids = array_values(array_unique($roomIds));
        //获取所有cbd房间id
        $this->set_es_data_by_ids($hot_room_ids);
    }

    /**
     * @params int[]
     * @return room[]
     * @desc 从RoomServices拷贝过来的，加点东西
     * @author zxiaofee
     * @date 2021.12.28
     */
    public function set_es_data_by_ids($ids)
    {
        if (empty($ids)) {
            return [];
        }

        $data = $this->model_room->get_rooms_by_ids($ids);
        $roomLabelRes = $this->model_room->getRoomLableByRoomIds($ids);
        $roomLabelMap = array_column($roomLabelRes, null, 'room_id');
        $data = array_column($data, null, 'room_id');

        // 房间日榜第一
        $dayRankTop1 = $this->model_finance_room_wealth->get_room_charts(1,0,1);
        $dayRankTop1 = array_keys($dayRankTop1);

        // 房间日榜icon
        $dayRankLabel = $this->model_room->getRoomRecommendLabelById(3, [ 'new_animate_resource', 'animate_resource' ]);

        $allRoomIds = [];
        $systemFilterRoomIds = [];

        $allRoomHotIdData = [];
        foreach ($ids as $v) {
            if(empty($data[$v])) {
                continue;
            }
            $dataInfo = $data[$v];
            //设置主麦userid 取热门时要大于0
            $dataInfo['host_micro_user_id'] = $this->model_room_host_micro->get_user_id($v) ?? 0;
            //设置麦数 取热门时要大于4
            $dataInfo['micro_user_count'] = $this->modelRoomMicro->getMicroUserCount($v)??0;

            //获取房间动态背景
            $roomInfo = $this->model_room->get_room($v);
            $dataInfo['dynamic_cover'] = $roomInfo['dynamic_cover'];
            //获取房间Pk
            $dataInfo['pk_status'] = '';

            $tmpRoomUserAvatar = [];

            //获取主持麦头像
            $hostMicroId = $this->model_room_host_micro->get_user_id($v);
            $hostMicroInfo = $this->modelUser->get_user($hostMicroId);
            if ($hostMicroInfo) {
                $tmpRoomUserAvatar[] = [ 'pic' => $hostMicroInfo['thumbnails'], 'gender' => $hostMicroInfo['gender'], 'adapt_images' => isset($hostMicroInfo['images'][0]) && $hostMicroInfo['images'][0] ? $hostMicroInfo['images'][0].'?x-oss-process=image/resize,w_60,m_lfit' : '' ];
                $dataInfo['hostMicroAva'] = $this->mallGoods->getGoodsAttire($hostMicroId);
            }
            //获取房间在线用户
            $inRoomUserId = $this->model_room_user->get_usersids($v);
            if(is_array($inRoomUserId)) {
                $inRoomUserIdSlice = array_slice($inRoomUserId, 0, 20);
                if (count($inRoomUserIdSlice) > 0) {
                    foreach ($inRoomUserIdSlice as $uId) {
                        $roomUserInfo = $this->modelUser->get_user($uId);
                        $tmpRoomUserAvatar[] = [ 'pic' => $roomUserInfo['thumbnails'], 'gender' => $roomUserInfo['gender'], 'adapt_images' => isset($roomUserInfo['images'][0]) && $roomUserInfo['images'][0] ? $roomUserInfo['images'][0].'?x-oss-process=image/resize,w_60,m_lfit' : ''];
                    }
                }
            }
            $dataInfo['online_list'] = $tmpRoomUserAvatar;
            $dataInfo['hot'] = $dataInfo['hot_sort'] = $this->model_room_hot->get($dataInfo['room_id']);

            $dataInfo['online_count'] = $this->model_room_user->get_users_count($dataInfo['room_id']);
            $roomUser = $this->modelUser->get_user($dataInfo['user_id']);
            if(empty($dataInfo['image'])) $dataInfo['image'] = $roomUser['thumbnails'][0] ?? '';
            $dataInfo['gender'] = $roomUser['gender'] ?? 0;
            //设置求陪伴
            $dataInfo['accompany_tag'] = 0;

            //获取所有在麦上的用户头像
            $host_mic_user_id = $this->model_room_host_micro->get_user_id($dataInfo['room_id']);
            $host_user = $this->modelUser->get_user($host_mic_user_id);
            $mics_images = [];
            if(!empty($host_user['images'])){
                $mics_images[] = $host_user['images'][0];
            }
            $mic_users = $this->modelRoomMicro->get_micros($dataInfo['room_id'] ,$dataInfo['room_type']['id']);
            foreach ($mic_users as $mic_user){
                if(!empty($mic_user['user_id'])){
                    $val = $this->modelUser->get_user($mic_user['user_id']);
                    if(!empty($val['images'])){
                        $mics_images[] = $val['images'][0];
                    }
                }
            }
            $dataInfo['mic_images'] = $mics_images ?? [];

            //在线用户
            $online_user_ids = $this->model_room_user->get_usersids($dataInfo['room_id']);
            $online_user_ids = empty($online_user_ids) ? [] : $online_user_ids;
            $dataInfo['online_man_count'] = 0;
            foreach ($online_user_ids as $online_user_id){
                if($this->modelUser->get_user($online_user_id)['gender'] == 1){
                    $dataInfo['online_man_count'] ++;
                }
            }
            $dataInfo['online_woman_count'] = $dataInfo['online_count'] - $dataInfo['online_man_count'];

            // 后台配置的优先级大于自动配置
            $dataInfo['recommend_label'] = '';
            $dataInfo['recommend_svag'] = '';
            $dataInfo['recommend_special'] = '';

            if(in_array($v, $dayRankTop1)) {
                $dataInfo['recommend_label'] = $dayRankLabel['animate_resource'] ?? '';
                $dataInfo['recommend_svag'] = $dayRankLabel['new_animate_resource'] ?? '';
            }

            if(isset($roomLabelMap[$v])) {
                $dataInfo['recommend_label'] = $roomLabelMap[$v]['animate_resource'];
                $dataInfo['recommend_svag'] = $roomLabelMap[$v]['new_animate_resource'];
                $dataInfo['recommend_special'] = $roomLabelMap[$v]['special_animate_resource'];
            }
            //将房间数据保存到es
            $this->model_room_hot->saveRoomHotToEs($dataInfo);
            $allRoomIds[] = $v;
            //如果在系统过滤名单里首页就过滤掉 或者麦数小于5首页也过滤调
            $allRoomHotIdData[] = [
                'r' =>  $dataInfo['room_id'],
                't' =>  $dataInfo['room_type']['id'],
                'h' =>  $dataInfo['hot_sort'],
                'b' =>  $roomInfo['business_type'],
                'm' => (in_array($v, $systemFilterRoomIds) || $dataInfo['host_micro_user_id'] <= 0 || (!in_array($dataInfo['room_type']['id'], [1, 13]) && $dataInfo['micro_user_count'] < 4))
            ];
        }

        $this->model_room_hot->setAllRoomHotIdData(json_encode($allRoomHotIdData));

        //从es里删除没用的房间数据
        $this->model_room_hot->delRoomHotFromEs($allRoomIds);
        return true;
    }

    //获取房间麦上用户
    public function getRoomMicroUser($roomId) {
        $list = [];
        $list['host'] = [];
        $list['norn'] = [];
        $list['all'] = [];
        //主持麦
        $userId = $this->model_room_host_micro->get_user_id($roomId);
        if(!empty($userId)) {
            $list['host'][] = $userId;
            $list['all'][] = $userId;
        }
        //普通麦
        for ($i = 0; $i < 8; $i++){
            $userId = $this->modelRoomMicro->get_user_id($roomId, $i);
            if(!empty($userId)) {
                $list['norn'][] = $userId;
                $list['all'][] = $userId;
            }
        }

        return $list;
    }

}
